package com.six.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.six.core.entity.Order;
import com.six.core.entity.PayLog;
import com.six.core.vo.Result;
import com.six.order.dao.OrderMapper;
import com.six.order.dao.PayLogMapper;
import com.six.order.dao.WeiXinMapper;
import com.six.order.feign.GoodsFeign;
import com.six.order.util.HttpClient;
import com.six.core.vo.GoodsNumUpdateVo;
import com.six.order.vo.dto.PayOrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.github.wxpay.sdk.WXPayUtil;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Description:
 * @author:LiWei
 * @date:2023年03月04日10:42
 */
@Service
public class WeiXinService {
    @Autowired
    private WeiXinMapper weiXinMapper;

    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private PayLogMapper payLogMapper;
    @Autowired
    private GoodsFeign goodsFeign;

    @Value("${weixin.appid}")
    private String appid;
    @Value("${weixin.mch_id}")
    private String muchid;
    @Value("${weixin.api_key}")
    private String apikey;

    public static void main(String[] args) {
        System.out.println(new WeiXinService().appid);
    }

    public Result createNative(String orderId) {
        double price = 0;
        StringBuffer goodsName = new StringBuffer();
        List<PayOrderVo> payOrderVoList = orderMapper.payOrder(orderId);
        for (PayOrderVo orderVo : payOrderVoList) {
            goodsName.append(orderVo.getGoodsName()+"、");
            price += orderVo.getPrice();
        }
        String newGoodsName = goodsName.substring(0, goodsName.length() - 1);
        PayOrderVo payOrderVo = new PayOrderVo();
            payOrderVo.setPrice(price);
            payOrderVo.setGoodsName(newGoodsName);

        if(payOrderVo.getPrice()!=0){
            Map<String, String> params = new HashMap<>();
            params.put("appid",appid);
            params.put("mch_id",muchid);
            //随机生成
            params.put("nonce_str",WXPayUtil.generateNonceStr());
            //需要修改，这是订单名字
            params.put("body",payOrderVo.getGoodsName());
            //订单的id
            params.put("out_trade_no",orderId);
            //定义价格("total", total_fee)
            params.put("total_fee",new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue()+"");
            //服务器的ip
            params.put("spbill_create_ip","127.0.0.1");
            //支付后跳转的路径
            params.put("notify_url","http://localhost:8080/pay/back");
            //支付类型
            params.put("trade_type","NATIVE");

            try {
                //远程调用微信支付的接口
                HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                //设置http协议的请求
                httpClient.setHttps(true);
                //设置xml格式的参数
                httpClient.setXmlParam(WXPayUtil.generateSignedXml(params,apikey));

                httpClient.post();

                //返回结果
                String content = httpClient.getContent();
                //转化为map
                Map<String, String> map = WXPayUtil.xmlToMap(content);
                System.out.println("map = " + map);
                if (map.get("result_code").equals("SUCCESS")) {
                    Map<String, Object> result = new HashMap<>();
                    result.put("codeUrl",map.get("code_url"));
                    //总费用
                    result.put("price",payOrderVo.getPrice());
                    //订单名字
                    result.put("title",payOrderVo.getGoodsName());
                    //订单id
                    result.put("orderId",orderId);
                    return new Result(200,"获取二维码成功",result);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return new Result(500,"订单失效","00000000000000");
    }


    public Result queryPayState(String orderId) {
        Map<String, String> params = new HashMap<>();
        params.put("appid",appid);
        params.put("mch_id",muchid);
        params.put("out_trade_no",orderId);
        params.put("nonce_str",WXPayUtil.generateNonceStr());
        try {
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            httpClient.setHttps(true);
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(params,apikey));

            httpClient.post();
            String content = httpClient.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            System.out.println("map = " + map);
            if (map.get("trade_state").equals("SUCCESS")) {
                //修改订单状态
                Order order = new Order();
                order.setPaystate(0);
                order.setIsDeleted(0);
                QueryWrapper<Order> wrapper = new QueryWrapper<>();
                wrapper.eq("orderid",orderId);
//                wrapper.eq("paystate",1);
                weiXinMapper.update(order,wrapper);
                //往支付日志表中添加支付日志信息
                PayLog payLog = new PayLog();
                payLog.setOrderid(orderId);
                payLog.setPayTime(new Date());
                payLog.setTotalFee(new BigDecimal(map.get("total_fee")));
                payLog.setTransactionId(map.get("transaction_id"));
                payLog.setTradeState(map.get("trade_state"));
                payLog.setPayType(0);
                int insert = payLogMapper.insert(payLog);
                //查询该订单下的商品信息，修改对应商品的库存
                QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("orderid",orderId).select("goodsid","goodsnum");
                List<Order> orderList = orderMapper.selectList(queryWrapper);
                List<GoodsNumUpdateVo> list = new ArrayList<>();
                for (Order order1 : orderList) {
                    GoodsNumUpdateVo goodsNumUpdateVo = new GoodsNumUpdateVo();
                    goodsNumUpdateVo.setGoodsid(order1.getGoodsid());
                    goodsNumUpdateVo.setGoodsnum(order1.getGoodsnum());
                    list.add(goodsNumUpdateVo);
                }
                //调用feign接口修改商品库存
                Integer i = goodsFeign.updateGoodsNum(list);
                return new Result(200,"支付成功","1111111111");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result(500,"支付失败",000000);
    }

}








